function HostUpsertDialogCtrl($scope, dialog, Util, Host,Cluster,ztree) {
    $scope.close = function (result) {
        dialog.close(result)
    };

    $scope.do_submit = function () {
        if ($scope.host) {
            if($scope.host.host_name&&$scope.host.host_name.indexOf(" ")!=-1){
                alert('主机名不能包含空格!');
                return;
            }
            $scope.loading = true;
            Host.update({id: $scope.host.id, host: $scope.host},function(data){
                angular.forEach(dialog.context_scope.hosts,function(item,i){
                    if(item.id == data.id){
                        dialog.context_scope.hosts[i] = data;
                    }
                })
                ztree.edit_node_name("h"+$scope.host.id,$scope.host.host_name);
                dialog.close();
            },function(e){
                Util.alert(e.data);
                $scope.loading = false;
            })
        }
    };

    var selected_host = dialog.context_scope.selected_host;
    if (selected_host) {
        $scope.title = "修改主机";
        $scope.action = "$update";
        $scope.host = angular.copy(selected_host);
    }

    Cluster.list({}, function (data) {
        $scope.clusters = data;
        angular.forEach($scope.clusters, function (item) {
            if (item.id === $scope.host.cluster.id) {
                $scope.host.cluster = item;
            }
        });
    });


}

function HostActivateDialogCtrl($scope, dialog, Host, Cluster, ztree) {
    //这里要解除绑定，用户在点击保存前不需要更新列表数据
    $scope.host = angular.copy(dialog.context_scope.selected_host);

    $scope.close = function (result) {
        dialog.close(result)
    }

    $scope.loading = false;
    $scope.do_submit = function () {
        if($scope.host.host_name&&$scope.host.host_name.indexOf(" ")!=-1){
            alert('主机名不能包含空格!');
            return;
        }
        $scope.loading = true;

        Host.activate({id: $scope.host.id, host: $scope.host}, function (data) {
            dialog.context_scope.selected_host.cluster = $scope.host.cluster;
            dialog.context_scope.selected_host.status = 2;
            dialog.close();

            ztree.addhost({
                id: data.id,
                name: data.host_name,
                url: "#/host/" + data.id
            }, $scope.host.cluster.id);
            dialog.close();

        })
    }
    $scope.$watch("host.usedhcp",function(usedhcp){
        if(usedhcp){
            $scope.host.address = null;
            $scope.host.gateway = null;
            $scope.host.netmask = null;
            $scope.host.dns1 = null;
        }
    });
    $scope.title = "主机激活配置";

    Cluster.list({}, function (data) {
        $scope.clusters = data;
//        $scope.host.cluster = $scope.clusters[0];
    });

    $scope.host.powertool = 0;
}

/********************* Task Calendar Start ******************************/
function TaskCalendarDialogCtrl($scope, dialog, DataCenter, Util, VM, $filter) {
    $scope.close = function (result) {
        dialog.close(result)
    };

    DataCenter.hosts({id: 1, scope:'all'}, function(hosts){
        $scope.hosts = hosts.data;
    });

    DataCenter.vms({id:1,scope:'all'},function(vms){
        $scope.vms = vms.data;
        angular.forEach($scope.vms,function(vm){
            vm.displayname = vm.name + "(" + $filter('vmstatus')(vm.status) + ")";
            if (dialog.context_scope.selected_event){
                var kwargs = dialog.context_scope.selected_event.kwargs;
                var obj = eval("("+kwargs+")");
                if(vm.id == obj.instid){
                    $scope.event.vm = vm;
                }
            }
        });
    });

    DataCenter.schedule_tasks({id:dialog.context_scope.datacenter.id},function(tasks){
        $scope.tasks = tasks.data;

        if (dialog.context_scope.selected_event){
            angular.forEach($scope.tasks, function(task){
                var kwargs = dialog.context_scope.selected_event.kwargs;
                var obj = eval("("+kwargs+")");
                $scope.event.snapshotname = obj['snapshotname']
                if(task.value == obj.task_name){
                    $scope.event.task = task;
                }
            });
        }
    });

    $scope.priorities = [{name: '一般', value: 0}, {name: '普通', value: 1}, {name: '高级', value: 2}, {name: '紧急', value: 3}];
//    $scope.priorities = [
//        {name: '低', value: 10},
//        {name: '普通', value: 5},
//        {name: '高', value: 0}
//    ];
    $scope.durations = [
        {name: '不限', value: 0},
        {name: '1分钟', value: 1 * 60 * 1000},
        {name: '3分钟', value: 3 * 60 * 1000},
        {name: '5分钟', value: 5 * 60 * 1000},
        {name: '10分钟', value: 10 * 60 * 1000},
        {name: '20分钟', value: 20 * 60 * 1000},
        {name: '30分钟', value: 30 * 60 * 1000},
        {name: '1小时', value: 60 * 60 * 1000},
        {name: '2小时', value: 2 * 60 * 60 * 1000},
        {name: '3小时', value: 3 * 60 * 60 * 1000},
        {name: '5小时', value: 5 * 60 * 60 * 1000},
        {name: '8小时', value: 8 * 60 * 60 * 1000},
        {name: '10小时', value: 10 * 60 * 60 * 1000},
        {name: '12小时', value: 12 * 60 * 60 * 1000},
        {name: '24小时', value: 24 * 60 * 60 * 1000},
        {name: '48小时', value: 24 * 60 * 60 * 1000},
        {name: '72小时', value: 72 * 60 * 60 * 1000}
    ];
    $scope.duration = 0;
    $scope.start_time = "08:00";
    $scope.event = {
        priority: 3
    }

    if (dialog.context_scope.selected_event) {
        $scope.title = "更新任务";
        $scope.action = 'update_task';
        copy($scope.event, dialog.context_scope.selected_event, 'title', 'start','end', 'description', 'task', 'vm', 'id', 'queue', 'kwargs');

        date = $scope.event.start;
        $scope.event.start = date.format("yyyy-MM-dd hh:mm:ss");
        $scope.event.starttime = date.format("hh:mm:ss");
    } else {
        $scope.title = "添加任务";
        $scope.action = 'create_task';
        if (dialog.context_scope.selected_date) {
            $scope.event.start = dialog.context_scope.selected_date.format("yyyy-MM-dd hh:mm:ss");
            today = new Date();
            $scope.event.starttime = today.format("hh:mm:ss");
        }
    }

    function event_duration() {
        var start = $scope.event.start;
        var start = new Date(Date.parse(start));
        var time_ms = start.getTime();
        if ((/^(\d{2})\:(\d{2})$/gi).test($scope.start_time)) {
            var constant = 60 * 1000;
            var ms = +RegExp.$1 * 60 * constant + RegExp.$2 * 60 * constant;
            time_ms += ms;
        }
        return {
            start: new Date(time_ms),
            end: new Date(time_ms + $scope.duration)
        };
    }

    $scope.create_task = function () {
        var starttime = new Date($scope.event.start);
        if(starttime<=new Date()){
            Util.alert("任务时间应晚于当前时间");
            return false;
        }
        DataCenter.add_schedule_task({id:dialog.context_scope.datacenter.id,task: $scope.event}, function (event) {
            if(event.status==200){
                data = event.data
                var event = {
                    "id": data.id,
                    "title": data.name,
                    "start": data.start,
                    "task": data.task,
                    "kwargs": data.kwargs,
                    "queue": data.queue,
                    "description": data.desc,
                    "hide": false,
                    "allDay": true
                }

                dialog.context_scope.events.push(event);
                dialog.close();
            }else{
                Util.alert(event.msg);
                dialog.close();
            }
        });
    };

    $scope.update_task = function () {
        var starttime = new Date($scope.event.start);
        if(starttime<=new Date()){
            Util.alert("任务时间应晚于当前时间");
            return false;
        }
        DataCenter.update_schedule_task({id: dialog.context_scope.datacenter.id, task: $scope.event}, function (data) {
            if(data.status=='200'){
                angular.forEach(dialog.context_scope.events, function (event) {
                    if(event.id==$scope.event.id){
                        var index = dialog.context_scope.events.indexOf(event);
                        $scope.event.id = data.newid;
                        $scope.event.kwargs = data.kwargs;
                        dialog.context_scope.events.splice(index,1);
                        dialog.context_scope.events.push($scope.event);
                    }
                });
                dialog.close();
            }else{
                Util.alert('修改任务失败');
            }
        });
    };

    $scope.do_submit = function () {
        $scope[$scope.action]();
    };

    $scope.changevm = function(){
        if($scope.event.task && $scope.event.task.value=='snapshot_restore'){
            VM.snapshot_list({id:$scope.event.vm.id,scope:'all'},function(data){
                $scope.snapshots = data.data;
            });
        }
    };

    $scope.changetask = function() {
        if($scope.event.task.value=='create_vm'){
            Util.dialog("vm_workflow.html", 'VMWorkflowDialogCtrl', $scope, {backdropClick: false});
        }
        if($scope.event.task.value == 'snapshot_restore'){
            $scope.snapshotvms = $scope.vms.filter(function(vm){return vm.snapshot_set.length>0 });
            if($scope.event.vm && !$scope.snapshots){
                VM.snapshot_list({id:$scope.event.vm.id,scope:'all'},function(data){
                    $scope.snapshots = data.data;
                });
            }
            VM.snapshot_list({id:dialog.context_scope.selected_vm.id,scope:'all'},function(data){
                $scope.snapshots = data.data;
            })
        }
    };

    function copy(dst, src) {
        //angular.extend($scope.event, dialog.context_scope.selected_event);  //Here is a bug.
        if (arguments.length > 2) {
            var property_names = [].slice.call(arguments, 2);
            for (var i = 0; i < property_names.length; i++) {
                var name = property_names[i];
                dst[name] = src[name];
            }
        } else {
            angular.extend(dst, src);
        }
    }
}
/********************* Task Calendar End ******************************/

/********************* VM Management Start ******************************/

function VMWorkflowDialogCtrl($scope,Cluster,VM, dialog, Util,Proposal,Storage,Network,$pollingPool,ztree,$filter,User) {

    $scope.close = function (result) {
        dialog.close(result)
    };

    $scope.actiontype = 'createvm'
    if(dialog.context_scope.event){
        if(dialog.context_scope.event.task=='create_vm'){
            $scope.actiontype = 'createtask'
        }
    }

    User.list({scope:'all'},function(data){
        $scope.users = data.data;
    })

    $scope.current_step = 1;
    $scope.steps = ["虚拟机设置", "操作系统类型", "选择方案", "确认创建"];
    $scope.graphics_types = ['vnc','spice'];

    $scope.ostypes = window.OSTYPES;

    $scope.template = 'image';//默认选中模板
    $scope.config = 'p';  //默认选中方案
    Cluster.list({scope:'notempty'},function(data){
        $scope.clusters = data;
    })

    $scope.$watch('inst.cluster',function(c){
        if(c){
            Storage.isos({cluster_id: c.id},function(data){
                $scope.isos = data;
            },function(e){
                //need to do nothing
            })
        }
    })


    $scope.inst = {fixedip:{id:0},disk_bus:'ide'};//mock for null fixip
    $scope.inst.graphics_type = 'vnc';
    $scope.load_fixedips = function(n){
        if(n){
           if(n.networktype==2|| n.networktype==3){
            if(n.rundhcp){
                Network.fixedips({id: n.id},function(data){
                   $scope.fixedips = data;
                });
            }
        }
        }

    }
    Proposal.list({scope:'all'},function(data){
        $scope.proposals = data.data;
    })
    $scope.loadstorage = function(){
        Cluster.storages({id:$scope.inst.cluster.id,scope:'all',alive:true},function(data){

            $scope.storages = $.grep(data.data,function(d){
                var filter = d.type != 'iso';
                if($scope.template == 'image'&&$scope.inst.source){//如果选择了模板，则过滤掉iscsi存储
                    filter = filter && d.protocol != 'iscsi';
                }
                return filter;
            })
            $scope.storage = data.data[0];
        })
    }

    $scope.loadtemplate = function(){
        if($scope.inst.cluster){
            Cluster.templates({id:$scope.inst.cluster.id,scope:'all',status:'alive'},function(data){
                $scope.templates = $.grep(data.data,function(t){
                    return t.storage.protocol!='local'|| ($scope.inst.host&&t.storagehost == $scope.inst.host.ip);//只显示选中host的本地镜像存储,CVIR-79
                })

            })
        }

    }
    $scope.loadnetwork = function(){
        Cluster.networks({id:$scope.inst.cluster.id,scope:'all'},function(data){
            $scope.networks = data.data;
            $scope.network = data.data[0];
        })
    }


    $scope.proposalchange = function(p){
        angular.forEach($scope.storages,function(item){
            if(item.id=== p.storage.id){
                $scope.inst.storage = item;
            }
        })

        angular.forEach($scope.networks,function(item){
            if(item.id=== p.network.id){
                $scope.inst.network = item;
            }
        })

        if($scope.inst){
            $scope.inst.cpu = p.cpu;
            $scope.inst.mem = p.memory;
            $scope.inst.disk = p.disk;
        }

    }

    $scope.storagechange = function(){
        if($scope.inst.storage.protocol == 'iscsi'){
            $scope.showlun = true
            $scope.inst.disk_bus = 'ide';
            $scope.inst.disk = '';
            Storage.luns({'target':$scope.inst.storage.target, 'host':$scope.inst.storage.host,
                'username':$scope.inst.storage.username,'password':$scope.inst.storage.password},function(data){
                $scope.inst.luns = data.data;
            });
        }else{
            $scope.showlun = false;
        }
    }

    $scope.lunchange = function(){
        var lun = $scope.inst.lun;
//        $scope.inst.disk_bus = 'ide';
        $scope.inst.disk = lun.size;
    }

    var change_style = function () {
        for (var i = 0; i < $scope.steps.length; i++) {
            var j = i + 1;
            if (j < $scope.current_step) {
                $scope['step0' + j + '_style'] = "btn-success";
            } else if (j > $scope.current_step) {
                $scope['step0' + j + '_style'] = "";
            } else {
                $scope['step0' + j + '_style'] = "btn-info";
            }
        }
    }

    $scope.jump = function (n) {
        $scope.current_step = n;
    }

    $scope.$watch('current_step', function (n) {
        change_style();
    });

    $scope.prev_step = function () {
        $scope.current_step -= 1;
    };
    $scope.next_step = function () {

        $scope.current_step += 1;

    };

    $scope.$watch('current_step',function(new_value){
        if(new_value == 2){
            $scope.loadtemplate();
        }
        if(new_value == 3){
            $scope.loadstorage();
            $scope.loadnetwork();
        }
    })

    $scope.do_upsert = function () {
        if ($scope.inst) {
            dialog.close();
            VM.create({inst:$scope.inst,template:$scope.template},function(data){
               $pollingPool.add_activity_callback(data.activity,function(){
                   dialog.context_scope.vms.push(data);
                   ztree.addvm({
                       id: data.id,
                       name: data.name,
                       url: "#/vm/" + data.id,
                       icon:"/static/images/vmstatus/"+$filter('lowercase')(data.status)+".png"
                   }, data.host.id);
               })

            });

        }
//
    };
    $scope.add2task = function () {
        if ($scope.inst) {
            dialog.close();
            var inst = $scope.inst;
            var params = {'name':inst.name,'cluster':inst.cluster.name,'host':inst.host.host_name,'desc':inst.desc,'display':inst.graphics_type,
            'iso':inst.source.name,'cpu':inst.cpu||proposal.cpu};
            dialog.context_scope.params=params;
        }
    };

}

function VMConfigDialogCtrl($scope, VM, dialog, Util,Cluster,Network,$pollingPool,BackupStrategy,$filter,User) {
    $scope.close = function (result) {
        dialog.close(result)
    }
    $scope.vm = angular.copy(dialog.context_scope.selected_vm);
    $scope.originvm = dialog.context_scope.selected_vm;
    $scope.ostypes = window.OSTYPES;
    angular.forEach($scope.ostypes,function(item){
        if(item.name==$scope.vm.os_type){
            $scope.vm.os_type = item;
        }
    })
    User.list({scope:'all'},function(data){
        $scope.users = data.data;
        if($scope.vm.user){
            //TODO too many users may cause a slow performance
            for(var i=0;i<$scope.users.length;i++){
                if($scope.users[i].username == $scope.vm.user.username){
                    $scope.vm.user = $scope.users[i];
                    break;
                }
            }
        }
    })

    function open_disk_dialog(ctrl){
        $scope.open_new_disk = true;
        Util.dialog("/static/partials/vms/new_disk.html", ctrl, $scope, {backdropClick: false, dialogClass: 'modal mini'});
    }

    $scope.new_disk = function(){
        $scope.title = "修改虚拟机磁盘";
        $scope.hasvdisk = true;

        open_disk_dialog('newdisk_config_ctrl');
    }

    $scope.update_disk = function(){
        $scope.title = "创建虚拟机磁盘";

        open_disk_dialog('update_disk_ctrl');
    }

    $scope.attach_disk = function(){
        Util.dialog("/static/partials/clusters/attach_vdisk.html", "", $scope, {backdropClick: false, dialogClass: 'modal mini'});
    }

    $scope.delete_disk = function(){
        Util.confirm('确定要删除吗?',function(){
            if($scope.selected_disk.device_type=='disk'){
                 Util.confirm('删除关联的存储文件吗？',function(){
                     delete_disk(VM,$scope,$pollingPool,true,dialog);
                })
            }else{
                delete_disk(VM,$scope,$pollingPool,true,dialog);
            }
        })
    }

    //for add button disable
    $scope.vdisklength = function(){
        var disks = $filter('activeitem')($scope.vm.vdisk_set);
        return disks.length > 3;
    }

    $scope.detach_disk = function(){
        Util.confirm('确定要和虚拟机解除关联吗?解除后虚拟机将不再使用当前磁盘',function(){
            delete_disk(VM,$scope,$pollingPool,false,dialog);
        })
    }


    //--------------init interfaces -----------------

    angular.forEach($scope.vm.interface_set,function(item){
        if (item.name=='eth0'){
            $scope.vm.interface1 = item;
        }
        if (item.name=='eth1'){
            $scope.vm.interface2 = item;
        }
        if (item.name=='eth2'){
            $scope.vm.interface3 = item;
        }
        if (item.name=='eth3'){
            $scope.vm.interface4 = item;
        }
    })
    $scope.vm.interface1 = $scope.vm.interface1||{};
    $scope.vm.interface2 = $scope.vm.interface2||{};
    $scope.vm.interface3 = $scope.vm.interface3||{};
    $scope.vm.interface4 = $scope.vm.interface4||{};
    $scope.vm.interface1.model = $scope.vm.interface1.model||'e1000';
    $scope.vm.interface2.model = $scope.vm.interface1.model||'e1000';
    $scope.vm.interface3.model= $scope.vm.interface1.model||'e1000';
    $scope.vm.interface4.model = $scope.vm.interface1.model||'e1000';
    if(!$scope.vm.interface1.mac){
        Network.random_mac({t:new Date()},function(data){
        $scope.vm.interface1.mac = data.mac;
        })
    }
    if(!$scope.vm.interface2.mac){
        Network.random_mac({t:new Date()},function(data){
        $scope.vm.interface2.mac = data.mac;
        })
    }
     if(!$scope.vm.interface3.mac){
        Network.random_mac({t:new Date()},function(data){
        $scope.vm.interface3.mac = data.mac;
        })
    }
    if(!$scope.vm.interface4.mac){
        Network.random_mac({t:new Date()},function(data){
        $scope.vm.interface4.mac = data.mac;
        })
    }


    Cluster.networks({id:$scope.vm.host.cluster.id,scope:'all'},function(data){
        $scope.networks = data.data;
        if($scope.vm.interface1.network){
         angular.forEach($scope.networks,function(n){
             if($scope.vm.interface1.network.id == n.id){
                 $scope.vm.interface1.network = n;
             }
         })
         }
        if($scope.vm.interface2.network){
             angular.forEach($scope.networks,function(n){
                 if($scope.vm.interface2.network.id == n.id){
                     $scope.vm.interface2.network = n;
                 }
             })
         }
        if($scope.vm.interface3.network){
             angular.forEach($scope.networks,function(n){
                 if($scope.vm.interface3.network.id == n.id){
                     $scope.vm.interface3.network = n;
                 }
             })
         }
        if($scope.vm.interface4.network){
             angular.forEach($scope.networks,function(n){
                 if($scope.vm.interface4.network.id == n.id){
                     $scope.vm.interface4.network = n;
                 }
             })
         }


        function init_fixip(interface,n,old){
            $scope.load_fixedips(interface, n,function(){
                if(interface.fixedip){
                   angular.forEach(interface.fixedips,function(item){
                    if(interface.fixedip.id == item.id){
                        interface.fixedip = item;
                    }
                    })
                }
            });

        }
        $scope.$watch("vm.interface1.network",function(new_value,old){
            init_fixip($scope.vm.interface1,new_value,old);
        })
        $scope.$watch("vm.interface2.network",function(new_value,old){
            init_fixip($scope.vm.interface2,new_value,old);
        })
        $scope.$watch("vm.interface3.network",function(new_value,old){
            init_fixip($scope.vm.interface3,new_value,old);
        })
        $scope.$watch("vm.interface4.network",function(new_value,old){
            init_fixip($scope.vm.interface4,new_value,old);
        })

    })


    $scope.vm.soundenable  = $scope.vm.soundcard?true:false;

    $scope.vm.watchdog = $scope.vm.watchdog || '';
    $scope.vm.dogaction = $scope.vm.dogaction || 'reset';

//    $scope.$watch("vm.nestedvt",function(newvalue){
//        $scope.vm.cpu_host_model = newvalue;
//    })

    var sitem;
    BackupStrategy.list({scope:'all'}, function(strategies){
            $scope.strategies = strategies.data;
            angular.forEach(strategies.data,function(item){
                if(item.id == $scope.vm.backup_policy.id){//匹配select列表的选中
                    sitem = item;
                }
            })

    });
    //备份策略被remove后，vm数据中还是会级联查询出备份策略信息，但是BackupStrategy.list中却不存在。
    //所以在这里如果不能匹配到list中的数据，则表示备份策略已经移除了
    $scope.vm.backup_policy = sitem;

    $scope.load_fixedips = function(interface,n,callback){
        if(n){
           if(n.networktype==2|| n.networktype==3){
            if(n.rundhcp){
                var include = interface.fixedip?interface.fixedip.id:null;
                Network.fixedips({id: n.id,include:include},function(data){
                   interface.fixedips = data;
                   callback();
                });
            }
        }
        }

    }
    //--------------init interfaces -----------------end

    $scope.select_disk = function(){
        $scope.selected_disk = this.disk;
    }
    $scope.do_update = function () {

        if ($scope.vm) {
            if($scope.vm.vcpu > 8){
                alert('cpu个数不能超过8个');
                return;
            }
            if($scope.vm.memory > 128*1024){
                alert('内存最大为128GB');
                return;
            }

            VM.update({id:$scope.vm.id,vm:$scope.vm},function(data){
                angular.forEach(dialog.context_scope.vms,function(item,i){
                    if(item.id == data.id){
                        dialog.context_scope.vms[i] = data;
                    }
                })

            })
        }
        dialog.close();
        Util.alert('修改在虚拟机(hypervisor)重启后生效');
    }
}

function delete_disk(resource,$scope,$pollingPool,cleanup,dialog){
    var id = $scope.vm?$scope.vm.id:$scope.selected_disk.storage.cluster;//从虚拟磁盘页面过来判断是否是vm的磁盘删除，还是游离磁盘删除,参见action_controllers.js 653行
    resource.delete_disk({id:id,disk:$scope.selected_disk,cleanup:cleanup},function(data){
        $pollingPool.add_activity_callback(data.activity,function(){
            //在虚拟机修改页面删除和解除都是移除界面，集群虚拟磁盘页面则更加cleanup来区分是否移除
            if($scope.fromcluster&&!cleanup){
                $scope.selected_disk.instance = null;
            }
            else{
                $scope.selected_disk.deleted = true;//通过filter移除界面记录
                //由于我们使用activeitem做界面更新，在磁盘被修改后，又没有点击保存。这时候我们要更新虚拟机列表中的虚拟机信息，保证再次打开虚拟机修改页面时
                //不会出现已经移除的磁盘数据
                if(dialog&&dialog.context_scope.selected_vm){
                    angular.forEach(dialog.context_scope.selected_vm.vdisk_set,function(item){
                        if(item.id==$scope.selected_disk.id){
                            item.deleted = true;
                        }
                    })
                }
            }
        })

    })
}

function newdisk_config_ctrl($scope,dialog,Cluster,Storage,VM,$pollingPool){
    $scope.close = function (result) {
        dialog.context_scope.open_new_disk = false;
         dialog.close(result);
     }
     $scope.update = false;
    $scope.fromcluster = dialog.context_scope.fromcluster;
    init_disk($scope,null,Cluster,Storage,dialog);
    $scope.disk.format = "qcow2";
    $scope.disk.device_type = 'disk';

    $scope.change_storage = function(){
        if($scope.disk.storage.protocol=='iscsi'){
            Storage.luns($scope.disk.storage,function(data){
                if(!dialog.context_scope.hasvdisk){
                    $scope.luns = data.data.filter(function(obj){return obj.type=='lun'});
                }else{
                    $scope.luns = data.data;
                }
                console.log($scope.luns)
                $scope.disk.format='raw';
                $scope.disk.bus='ide';
            });
        }else{
            $scope.disk.format='';
            $scope.disk.size='';
            $scope.disk.bus='';
        }
    }

    $scope.change_lun = function(){
        $scope.disk.size = ""+parseInt($scope.disk.lun.size)
        if($scope.disk.lun.id){
            $scope.disk.name = $scope.disk.lun.lunid
        }else{
            $scope.disk.name = ''
        }
    }

    $scope.handle_disk = function(){
        $scope.disk.created_at = new Date();
        if($scope.disk.device_type=='cdrom'){
            $scope.disk.size = 0;
            $scope.disk.max_size = 0;
            $scope.disk.name = 'cdrom';
            $scope.disk.isopath = $scope.disk.isopath ? $scope.disk.isopath.path : null;;  //isopath使用string，保持统一
        }


        //集群虚拟机磁盘页面新建功能是添加游离的磁盘
        var resource = $scope.fromcluster?Cluster.add_dissociate_disk:VM.add_disk;
        var id = $scope.fromcluster?dialog.context_scope.vm.host.cluster.id:dialog.context_scope.vm.id;//vm磁盘添加参数使用vm.id,游离磁盘添加参数使用cluster.id
        resource({id:id,disk:$scope.disk},function(data){
            //添加游离的磁盘只是插入数据库，不需要pollingpool的回调
            if($scope.fromcluster){
                dialog.context_scope.vdisks.push(data);
            }else{
                $pollingPool.add_activity_callback(data.activity,function(){
                    //这里既要更新修改窗口数据，也要修改vm列表数据
                    dialog.context_scope.vm.vdisk_set.push(data);
                    dialog.context_scope.originvm.vdisk_set.push(data);
                })
            }
            $scope.close();
        })


    }
}

//------------newdisk and update disk common function
function init_disk($scope,disk,Cluster,Storage,dialog){
    $scope.disk = angular.copy(disk)||{};

    $scope.disk.bus = $scope.disk.bus||'IDE';
    $scope.disk.cache = $scope.disk.cache||'default';
    $scope.disk.iomode = $scope.disk.iomode||'default';
    $scope.vm = dialog.context_scope.vm;

    //在虚拟磁盘页面，如果是游离磁盘则$scope.vm为空，我们通过选择的disk来获取cluster
    var cluster_id  = $scope.vm?$scope.vm.host.cluster.id: dialog.context_scope.selected_disk.storage.cluster;//这里的cluster已经是id了

    Cluster.storages({id:cluster_id,scope:'all'},function(data){
        console.log(data);
        $scope.storages = $.grep(data.data,function(d){
                return d.type != 'iso';
        })

    })

    if(!$scope.fromcluster){
            Storage.isos({cluster_id:dialog.context_scope.vm.host.cluster.id},function(data){
            $scope.isos = data;
            if($scope.disk){
                angular.forEach($scope.isos,function(item){
                    if(item.path==$scope.disk.isopath){  //匹配iso object
                        $scope.disk.isopath = item;
                    }
                })
            }
        })
    }


}
//-----------------------------
function update_disk_ctrl($scope,dialog,Cluster,Storage,VM){
     $scope.close = function (result) {
        dialog.context_scope.open_new_disk = false;
         dialog.close(result);
     }
    $scope.update = true;
    $scope.fromcluster = dialog.context_scope.fromcluster;
    init_disk($scope,dialog.context_scope.selected_disk,Cluster,Storage,dialog);

    var disk_size = $scope.disk.size;

    $scope.handle_disk = function(){

        if( parseInt($scope.disk.size)< disk_size){
            alert('磁盘容量不能小于原来的大小: ' + disk_size+"GB");
            return;
        }

        var disk = angular.copy($scope.disk);//处理默认值之前copy disk数据，不能影响界面显示
        //处理默认值
        disk.iomode = $scope.disk.iomode != 'default'?$scope.disk.iomode : null;//default传递到后台的数据是null，即不需要设置iomode
        disk.cache = $scope.disk.cache != 'default'?$scope.disk.cache: null;
        disk.isopath = $scope.disk.isopath ? $scope.disk.isopath.path : null;  //isopath使用string，保持统一

        var resource = VM.update_disk;
        var id = dialog.context_scope.vm?dialog.context_scope.vm.id:null;//如果有关联的vm

        //如果是从虚拟磁盘页面调用，且是游离磁盘（instance=null),则请求cluster.update_dissociate_disk
        if($scope.fromcluster){
            if(dialog.context_scope.selected_disk.instance==null){
                resource = Cluster.update_dissociate_disk;
                id = dialog.context_scope.selected_disk.storage.cluster;
            }
        }

        resource({id:id,disk:disk},function(data){
            $scope.close();
            var disk = dialog.context_scope.selected_disk; //selected_disk有两个来源，1.虚拟机磁盘修改页面，2.集群虚拟磁盘页面
            disk.size = $scope.disk.size;
            disk.bus = $scope.disk.bus;
        })

    }

    //no image
    //no snapshot
    //如果是游离磁盘则不会有关联的vm,所以我们要从vm开始判断
    $scope.resize_condition = $scope.disk.image || (dialog.context_scope.vm&&dialog.context_scope.vm.snapshot_set
        &&dialog.context_scope.vm.snapshot_set.length>0);
    if ($scope.resize_condition){
        $scope.disk_msg = "磁盘包含模板或者快照";
    }

}

function SaveAsTemplateDialogCtrl($scope, dialog, VM, Util,Cluster) {
    $scope.title = "存为模版";
    $scope.template = {};
    $scope.close = function (result) {
        dialog.close(result)
    };

    $scope.ostypes = OSTYPES;
    angular.forEach($scope.ostypes,function(item){
        if(item.name == dialog.context_scope.selected_vm.os_type){
            $scope.template.os_type = item;
        }
    })

    var cluster_id = dialog.context_scope.selected_vm.host.cluster.id
    Cluster.storages({id:cluster_id,scope:'all'},function(data){

        $scope.storages = $.grep(data.data,function(d){
            //TODO filter local storage
            return d.type != 'iso'&& d.protocol != 'iscsi';
        })
        $scope.storage = data.data[0];
    })

    $scope.save_template = function () {
        VM.save_template({id: dialog.context_scope.selected_vm.id, template: $scope.template},function(data){
            console.log(data);
            dialog.close();
        })
    };
}

function VMMigrateDialogCtrl($scope, dialog, VM, Util,Cluster,$pollingPool,ztree,$location,$filter) {
    $scope.title = "迁移虚拟机";
    $scope.close = function (result) {
        dialog.close(result)
    };

    $scope.vm = dialog.context_scope.selected_vm;
    $scope.migrate = {};

    Cluster.hosts({id: $scope.vm.host.cluster.id,scope:'all'}, function (data) {
        $scope.hosts = $.grep(data.data,function(item){
            return $scope.vm.host.id != item.id;
        })
//        $scope.mhost = $scope.hosts[0];
    });


    $scope.do_migrate = function () {

        dialog.context_scope.selected_vm.migrating = true;
        dialog.close();
        VM.migrate({id: $scope.vm.id, migrate: $scope.migrate},function (data) {
            $pollingPool.add_activity_callback(data.activity,function(){
                var path = $location.path();
                if(path.indexOf('/host')==-1){
                    dialog.context_scope.selected_vm.host = data.host;
                }else{
                    //先删除原来的树节点和列表记录
                    if(dialog.context_scope.vms){
                        var index = dialog.context_scope.vms.indexOf(data);
                        dialog.context_scope.vms.splice(index, 1);
                    }
                }

                ztree.deletenode('v' + data.id);

                //然后添加新的树节点（新的host)
                ztree.addvm({
                   id: data.id,
                   name: data.name,
                   url: "#/vm/" + data.id,
                   icon:"/static/images/vmstatus/"+$filter('lowercase')(data.status)+".png"
                }, data.host.id);

            })
            dialog.context_scope.selected_vm.migrating = false;

        },function(e){
            dialog.context_scope.selected_vm.migrating = false;
            Util.alert(Util.decode_error_msg(e.data));
        });
    };
}


/********************* VM Management End ******************************/

/********************* Network Management Start ******************************/

function NetworkConfigDialogCtrl($scope, dialog, Util, Network, Cluster,$pollingPool) {

    $scope.close = function (result) {
        dialog.close(result);
    }

    $scope.update = dialog.context_scope.update;
    $scope.save_method =  dialog.context_scope.save_method;//create or update

    $scope.select_network = function(){
        $scope.network.rundhcp = $scope.network.networktype==0;  //nat网络必须开启dhcp
    }

    function validate($scope){

        if($scope.network.rundhcp){
            var pattern = /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/g;
            if(!pattern.test($scope.network.dhcp_start)){
                alert('[dhcp开始]请输入正确的ip地址');
                return false;
            }
            //必须重新赋值？
            var pattern = /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/g;
            if(!pattern.test($scope.network.dhcp_end)){
                alert('[dhcp结束]请输入正确的ip地址');
                return false;
            }

        }
        return true;
    }

    $scope.do_upsert = function () {

        if (validate($scope)) {
            dialog.close();
            if($scope.update){
                Util.alert('注意：网络修改后，关联的虚拟机(hypervisor)需要重启后生效');
            }
            Network[$scope.save_method]({id:$scope.network.id,network:$scope.network},function(data){
                $pollingPool.add_activity_callback(data.activity,function(){
                    if($scope.update){
                        angular.forEach(dialog.context_scope.networks,function(item){
                            if(item.id == data.id){
                                dialog.context_scope.networks[dialog.context_scope.networks.indexOf(item)] = data;
                            }
                        })
                    }else{
                        dialog.context_scope.networks.push(data);
                    }
                })
            },function(e){
                $scope.error = e.data;
                Util.alert(e.data);
            });

        }
    };

    Cluster.list({},function(data) {
        $scope.clusters = data;
        //把cluster转换到resource对象，data是resource对象，这样界面可以做绑定
        if ($scope.network) {
            angular.forEach($scope.clusters, function (item) {
                if (item&&$scope.network.cluster&&item.id === $scope.network.cluster.id) {
                    $scope.network.cluster = item;
                }
            });
        }
    });

    if($scope.save_method == 'create'){
        //新建网络默认开启组播探测
        $scope.network = {cast_snoop:true};
    }else{
        $scope.network = angular.copy(dialog.context_scope.selected_network);
    }
    if(!$scope.network.netmask)
        $scope.network.netmask = "255.255.255.0";//子网掩码默认值
}

function FixedipDialogCtrl($scope, dialog, Util, Fixedip) {

    $scope.close = function(){
        dialog.close();
    }

    $scope.selected || ($scope.selected = {});
    $scope.page_size = 30;
    $scope.selected_network = dialog.context_scope.selected_network;
    $scope.service = function (start, limit) {
        Fixedip.list({id: $scope.selected_network.id, current_page: start, page_size: limit}, function (fixip) {
            $scope.fixedips = fixip.data;
            $scope.total_page = fixip.total_page;
            $scope.total_count = fixip.total_count;
        });
    };

    Util.paginate($scope, 'fixedips');

    $scope.do_add = function() {

        $scope.open_new_ip = true;
        Util.dialog("/static/partials/networks/_network_fixedip_dialog.html",
            'FixedipAddDialogCtrl', $scope, {dialogClass: 'modal mini'});
    }

    $scope.do_delete = function(){

        Util.bind($scope, 'fixedips').select(1, 100).confirm('你确定要移除它们吗，此操作将无法恢复!').then(function(fixedips){
            var fixedips_ids = fixedips.map(function(fixedip) {
                if (fixedip.allocated == 0)
                    return fixedip.id;
            });

            for (var i = 0; i < fixedips_ids.length; i++) {

                if (!fixedips_ids[i])
                    fixedips_ids.splice(i, 1);
            }

            Fixedip.delete_all({ids: fixedips_ids, networkid: $scope.selected_network.id,page_size: $scope.page_size},
                success = function(data) {
                    angular.forEach(fixedips,function(f){
                        f.deleted=true;
                    })
                    $scope.selected_network.dhcp_start = data.dhcp_start;
                    $scope.selected_network.dhcp_end = data.dhcp_end;
                });

        });
    };
}

function FixedipAddDialogCtrl($scope, dialog, Util, Fixedip) {

    $scope.close = function(){
        dialog.context_scope.open_new_ip = false;
        dialog.close();
    }

    $scope.tab1_show = true;
    $scope.tab2_show = false;

    $scope.selected_network = dialog.context_scope.selected_network;

    $scope.tab1_click = function() {
        $scope.tab1_show = true;
        $scope.tab2_show = false;
    }

    $scope.tab2_click = function() {
        $scope.tab1_show = false;
        $scope.tab2_show = true;
    }

    $scope.do_upsert = function() {

        dialog.close();

        var params = {address: $scope.fixedip.ipaddress, network_id: $scope.selected_network.id};
        if ($scope.tab1_show) {
            params = {start: $scope.fixedip.start, end: $scope.fixedip.end, network_id: $scope.selected_network.id};
        }

        Fixedip.create(params, function(data) {

            dialog.context_scope.fixedips = dialog.context_scope.fixedips.concat(data.data);
            dialog.context_scope.open_new_ip = false;
            dialog.context_scope.selected_network.dhcp_start = data.dhcp_start;
            dialog.context_scope.selected_network.dhcp_end = data.dhcp_end;
        }, function(msg) {
            $scope.error = msg.data;
            Util.alert(msg.data);
            dialog.context_scope.open_new_ip = false;
        });

    }

}


function SSHDialogCtrl($scope, dialog, Util, SecurityGroup) {

    $scope.close = function(){
        dialog.close();
    }

    $scope.selected_host = dialog.context_scope.selected_host;
    $scope.selected_host.username = "root";

    $scope.sleep = function(milliSeconds) {
        var startTime = new Date().getTime(); // get the current time
        while (new Date().getTime() < startTime + milliSeconds); // hog cpu
    };

    $scope.sleep(3000);
}


function SecurityGroupDialogCtrl($scope, dialog, Util, SecurityGroup) {

    $scope.close = function(){
        dialog.close();
    }
    $scope.update = dialog.context_scope.update;
    $scope.do_upsert = function () {

        if ($scope.securitygroup.id) {

            dialog.close();
            SecurityGroup.update({securitygroup: $scope.securitygroup}, function(data) {

                Util.update(dialog.context_scope.security_groups, [data]);
            }, function(msg) {

                $scope.error = msg.data;
                console.log(msg);
            });
        } else {

            dialog.close();
            SecurityGroup.create({securitygroup: $scope.securitygroup}, function(data) {

                dialog.context_scope.security_groups.push(data);
            }, function(msg) {

                if (msg.data.indexOf("name already exists") != -1) {

                    Util.alert("输入的网络安全组名称已经存在！");
                }
                $scope.error = msg.data;
                console.log(msg);
            });
        }
    };

    var security_group = jQuery.extend(true, {}, dialog.context_scope.selected_group);
    if (security_group.id) {
        $scope.title = "编辑配置网络安全组";
        $scope.action = "$update";
        $scope.securitygroup = security_group;
    } else {
        $scope.title = "配置网络安全组";
        $scope.action = "$save";
        $scope.securitygroup = {};
    }
}


function SecurityRuleDialogCtrl($scope, dialog, Util, SecurityGroup, SecurityRule) {
    $scope.close = function(){
        dialog.close();
    }
    $scope.do_upsert = function () {

        if ($scope.securityrule.dstportstart > $scope.securityrule.dstportend) {

            $scope.port_related_check = true;
            return;
        }

        if ($scope.securityrule.id) {

            dialog.close();
            SecurityRule.update({securityrule: $scope.securityrule}, function(data) {

                Util.update(dialog.context_scope.security_rules, [data]);
            }, function(msg) {

                $scope.error = msg.data;
                console.log(msg);
            });
        } else {
            dialog.close();
            SecurityRule.create({securityrule: $scope.securityrule},function(data){
                dialog.context_scope.security_rules.push(data);
            },function(e){
                $scope.error = e.data;
                console.log(e);
            });
        }
    };

    $scope.iptitle = '外部IP';
    $scope.porttitle = '外部端口';
    $scope.directionChange = function() {

        if ($scope.securityrule.direction.value == "in") {
            $scope.iptitle = 'VM IP';
            $scope.porttitle = 'VM端口';
        } else if ($scope.securityrule.direction.value == "out") {
            $scope.iptitle = '外部IP';
            $scope.porttitle = '外部端口';

        } else if ($scope.securityrule.direction.value == "inout") {
            $scope.iptitle = 'IP';
            $scope.porttitle = '端口';
        }
    }

    $scope.portocols = [
        {name: "TCP", value: "tcp"},
        {name: "UDP", value: "udp"},
        {name: "ICMP", value: "icmp"},
        {name: "ALL", value: "all"}
    ];

    $scope.directions = [
        {name: "VM -> 外部", value: "out"},
        {name: "外部 -> VM", value: "in"},
        {name: "VM <-> 外部", value: "inout"}
    ];

    var security_rule = angular.copy(dialog.context_scope.selected_rule||{});
    if (security_rule.id) {
        $scope.title = "编辑配置网络";
        $scope.action = "$update";
        $scope.securityrule = security_rule;

        for (var i = 0; i < $scope.portocols.length; i++) {

            if ($scope.securityrule.protocol == $scope.portocols[i].value) {

                $scope.securityrule.protocol = $scope.portocols[i];
            }
        }

        for (var i = 0; i < $scope.directions.length; i++) {

            if ($scope.securityrule.direction == $scope.directions[i].value) {

                $scope.securityrule.direction = $scope.directions[i];
            }
        }

    } else {
        $scope.title = "配置网络";
        $scope.action = "$save";
        $scope.securityrule = {priority:400};

        $scope.securityrule.protocol = $scope.portocols[0];
        $scope.securityrule.direction = $scope.directions[0];
    }

    SecurityGroup.get({scope: 'all'}, function(data) {

        $scope.groups = [];
        if (data.data.length <=  0) {
            Util.alert("网络安全组不存在，请先创建网络安全组！");
            dialog.close();
        }

        for(var i = 0; i < data.data.length; i++) {

            $scope.groups.push({name: data.data[i].name, value: data.data[i].id});

            // 修复bug CVIR-68 如果在网络安全组页面选中了某个网络安全组，则新增网络规则页面的网络组下拉列表默认为那个网络组
            if (dialog.context_scope.group_id) {

                if (data.data[i].id == dialog.context_scope.group_id) {
                    $scope.securityrule.group = $scope.groups[i];
                }
            }

            if (($scope.securityrule.group) && ($scope.securityrule.group.id == data.data[i].id)) {

                $scope.securityrule.group = $scope.groups[i];
            }
        }

        if(!$scope.securityrule.group && $scope.groups.length > 0)
            $scope.securityrule.group = $scope.groups[0];
    });
}

function RelatedDialogCtrl($scope, dialog, Util, DataCenter, VM, SecurityGroup) {
    $scope.close = function (result) {
        dialog.close(result);
    }
    $scope.selected || ($scope.selected = {});
    $scope.checked || ($scope.checked = {});
    $scope.page_size = 5;
    $scope.service = function (start, limit) {
        DataCenter.vms({id: 1, current_page: start, page_size: limit}, function (vms) {
            $scope.vms = vms.data;
            $scope.total_page = vms.total_page;
            $scope.total_count = vms.total_count;
        });
    };

    Util.paginate($scope, 'vms');

    $scope.global_interfaces = [];
    $scope.global_vmid = [];

    $scope.bodyclick = function(vm_instance) {

        VM.interfaces({id: vm_instance.id}, function(interfaces) {

            if (!$scope.check_in_array($scope.global_vmid, vm_instance.id)) {

                $scope.global_vmid.push(vm_instance.id);
                $scope.global_interfaces = $scope.global_interfaces.concat(interfaces);

                for (var i = 0; i < interfaces.length; i++) {

                    if (interfaces[i].securitygroups && $scope.check_in_array(interfaces[i].securitygroups, dialog.context_scope.port_id)) {

                        if(!$scope.checked[interfaces[i].id])
                            $scope.checked[interfaces[i].id] = true;
                    }
                }
            }

            $scope.interfaces = interfaces;
            $scope.interface_show = true;
        });

    }

    $scope.check_in_array = function(array, id) {

        for (var i = 0; i < array.length; i++) {

            if (id == array[i].id) {

                return true;
            }
        }
        return false;
    }

    $scope.do_upsert = function() {

        var items = $.grep($scope.global_interfaces, function(item) {
            return $scope.checked[item.id];
        });

        var interface_ids = items.map(function(interface){return interface.id;});
        SecurityGroup.relate_vm({id: dialog.context_scope.port_id, interface_ids: interface_ids}, function(data) {

            dialog.close();
        });
    }

    $scope.interfaceClick = function(interface) {

        $scope.checked[interface.id] = !$scope.checked[interface.id];
    }
}

/********************* Network Management End ******************************/

/********************* Storage Start ******************************/
function StorageConfigDialogCtrl($scope, dialog, Util, Storage,Cluster,$pollingPool) {
    $scope.close = function (result) {
        dialog.close(result);
    }

    function validate($scope){
        var protocol = $scope.storage.protocol;
//        var addresspatten = /^[a-z\.]$/g;
        var path = /^\/.*/g;
        var ippattern = /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/g;
        if(protocol == 'nfs'){
            if(!ippattern.test($scope.storage.host)){
                alert('请输入正确的主机地址(ip或者hostname)');
                return false;
            }
            if(!path.test($scope.storage.path)){
                alert('请输入正确的路径')
                return false;
            }
        }else if (protocol=='iscsi'){
            if(!ippattern.test($scope.storage.host)){
                alert('请输入正确的主机地址(ip或者hostname)');
                return false;
            }

        }else if(protocol=='cifs'){
            var cifspath = new RegExp("^\/\/.*");
            if(!cifspath.test($scope.storage.path)){
                alert('请输入正确的共享路径地址');
                return false;
            }

        }

        return true;
    }

    $scope.do_upsert = function () {
        if (validate($scope)) {
            $scope.saving = true;
            Storage.create($scope.storage,function(data){
                dialog.close();
                $pollingPool.add_activity_callback(data.activity,function(){
                    Storage.status({id:data.id},function(status){
                        data.status = 'running';
                        data.totalsize = status.size;
                        data.used = status.used;
                        dialog.context_scope.build_storage_path(data);
                        dialog.context_scope.storages.push(data);
                    })
                })

            },function(r){
                $scope.saving = false;
                $scope.error = r.data;
            })

        }
    };


    $scope.keypress = function(event){
        console.log(event);
        if(event.code==13){
            $scope.search_iscsi_target();
        }
    }

    $scope.change_target = function(){
        if($scope.storage){
            Storage.luns($scope.storage,function(data){
                $scope.storage.luns = data.data;
            });
        }else{
            Util.alert("please input host ip address")
        }
    }

    $scope.search_iscsi_target = function(){
        if($scope.storage.host){
            Storage.targets({'host': $scope.storage.host},function(data){
                $scope.storage.targets = data.data;
            });
        }else{
            alert("请输入主机地址");
        }
    }

    Cluster.list({},function(data){
       $scope.clusters = data;
    });

}

/********************* Storage End ******************************/
function ClusterConfigDialogCtrl($scope, Cluster, dialog, ztree,Util) {
    $scope.do_upsert = function () {
        var datacenter_id = ztree.get_select_node_data().did;
        Cluster.create({name: $scope.name, datacenter: datacenter_id}, function (data) {
            ztree.addcluster({
                id: data.id,
                name: data.name,
                url: "#/cluster/" + data.id
            });
            dialog.close();
        });
    };

    $scope.close = function (result) {
        dialog.close(result);
    }
}

function ComputeProposalDialogCtrl($scope, dialog, Util, Proposal, DataCenter) {
    $scope.close = function (result) {
        dialog.close(result);
    }

    $scope.update = function () {
        $scope.compute.network = $scope.networks.default
        $scope.compute.interface_type = $scope.iftypes.default.name
        Proposal.update($scope.compute, function (data) {
            $scope.close();
        });
    };

    var selected_compute = dialog.context_scope.selected_compute;
    if (selected_compute) {
        $scope.title = "修改计算方案";
        $scope.action = "$update";
        $scope.compute = selected_compute;
        DataCenter.networks({id: 1, current_page: 1, page_size: 10000}, function (networks) { //get all network records
            $scope.networks = networks.data;
            angular.forEach($scope.networks, function (network) {
                if (network.id == $scope.compute.network.id) {
                    $scope.networks.default = network;
                }
            });
        });
        $scope.iftypes = [
            {'name': 'e1000'},
            {'name': 'e1001'},
            {'name': 'pcnet'},
            {'name': 'virtio'},
            {'name': 'rtl8139'},
            {'name': 'ne2k_pci'}
        ]
        angular.forEach($scope.iftypes, function (iftype) {
            if (iftype.name == $scope.compute.interface_type) {
                $scope.iftypes.default = iftype;
            }
        });
    }
}

/********************* Proposal End ******************************/


/********************* Backup Strategy Start ********************/

function BackupStrategyDialogCtrl($scope, dialog, Util, BackupStrategy, Storage) {
    $scope.close = function (result) {
        dialog.close(result);
    }

    $scope.do_upsert = function () {

        dialog.close();
        if ($scope.backupstrategy.id) {
            BackupStrategy.update({id: $scope.backupstrategy.id, name: $scope.backupstrategy.name, type: $scope.backupstrategy.backuptype,
                    compress: $scope.backupstrategy.compress, compresslevel:$scope.backupstrategy.compresslevel,
                    remain: $scope.backupstrategy.remain, remaindays: $scope.backupstrategy.remaindays,
                    locationtype: $scope.backupstrategy.locationtype, localpath: $scope.backupstrategy.localpath,
                    storage: $scope.backupstrategy.storage, sftphost: $scope.backupstrategy.sftphost,
                    sftppath: $scope.backupstrategy.sftppath, sftpusername: $scope.backupstrategy.sftpusername,
                    sftppassword: $scope.backupstrategy.sftppassword, backuptime: $scope.backupstrategy.backuptime,
                    backupfrequency: $scope.backupstrategy.backupfrequency, weekday: $scope.backupstrategy.week,
                    monthday: $scope.backupstrategy.day},
                success = function (data) {

                    Util.update(dialog.context_scope.strategies, [data]);
                },
                error = function (msg) {

                    $scope.error = e.data;
                    console.log(e);
                });
        } else {

            BackupStrategy.create({name: $scope.backupstrategy.name, type: $scope.backupstrategy.backuptype,
                               compress: $scope.backupstrategy.compress, compresslevel:$scope.backupstrategy.compresslevel,
                               remain: $scope.backupstrategy.remain, remaindays: $scope.backupstrategy.remaindays,
                               locationtype: $scope.backupstrategy.locationtype, localpath: $scope.backupstrategy.localpath,
                               storage: $scope.backupstrategy.storage, sftphost: $scope.backupstrategy.sftphost,
                               sftppath: $scope.backupstrategy.sftppath, sftpusername: $scope.backupstrategy.sftpusername,
                               sftppassword: $scope.backupstrategy.sftppassword, backuptime: $scope.backupstrategy.backuptime,
                               backupfrequency: $scope.backupstrategy.backupfrequency, weekday: $scope.backupstrategy.week,
                               monthday: $scope.backupstrategy.day},
                success = function (data) {

                    dialog.context_scope.strategies.push(data);
                },
                error = function (msg) {

                    $scope.error = e.data;
                    console.log(e);
                });
        }
    };

    $scope.schedulechange = function(schedule) {

        if ($scope.backupstrategy.backupfrequency.value == 0) {

            $scope.permissionsweek = false;
            $scope.permissionsday = false;
            $scope.permissionstime = true;
        } else if ($scope.backupstrategy.backupfrequency.value == 1) {

            $scope.permissionsweek = false;
            $scope.permissionsday = false;
            $scope.permissionstime = true;
        } else if ($scope.backupstrategy.backupfrequency.value == 2) {

            $scope.permissionsweek = true;
            $scope.permissionsday = false;
            $scope.permissionstime = true;
        } else if ($scope.backupstrategy.backupfrequency.value == 3) {

            $scope.permissionsweek = false;
            $scope.permissionsday = true;
            $scope.permissionstime = true;
        }
    }

    $scope.remain_all = function() {

        $scope.remaindays_dis = true;
    }

    $scope.remain_days = function() {


        $scope.remaindays_dis = false;
    }

    $scope.location_local = function() {

        $scope.storage_dis = true;
        $scope.host_dis = true;
        $scope.path_dis = true;
        $scope.username_dis = true;
        $scope.password_dis = true;

        $scope.local_dis = false;

        $scope.local_req = true
        $scope.storage_req = false
        $scope.host_req = false
        $scope.path_req = false
        $scope.username_req = false
        $scope.password_req = false
    }

    $scope.location_storage = function() {

        $scope.storage_dis = false;
        $scope.host_dis = true;
        $scope.path_dis = true;
        $scope.username_dis = true;
        $scope.password_dis = true;

        $scope.local_dis = true;

        $scope.local_req = false
        $scope.storage_req = true
        $scope.host_req = false
        $scope.path_req = false
        $scope.username_req = false
        $scope.password_req = false
    }

    $scope.location_remote = function() {

        $scope.storage_dis = true;
        $scope.host_dis = false;
        $scope.path_dis = false;
        $scope.username_dis = false;
        $scope.password_dis = false;

        $scope.local_dis = true;

        $scope.local_req = false
        $scope.storage_req = false
        $scope.host_req = true
        $scope.path_req = true
        $scope.username_req = true
        $scope.password_req = true
    }

    $scope.compress_click = function() {

        if(!$scope.backupstrategy.compress) {

            delete $scope.backupstrategy.compresslevel;
        }
    }

    $scope.backupstrategy = jQuery.extend(true, {}, dialog.context_scope.selected_backupstrategy);

    Storage.get({}, function(data) {

        $scope.storages = [];
        for(var i = 0; i < data.length; i++) {

            if (data[i].type != "iso") {
                $scope.storages.push({name: data[i].name, value: data[i].id});
            }

            if (($scope.backupstrategy.storage) && ($scope.backupstrategy.storage.id == data[i].id)) {

                $scope.backupstrategy.storage = $scope.storages[i];
            }
        }
    });

    $scope.backupTypes = [
        {name: '冷备份', value: 0},
        {name: '热备份', value: 1}
    ];

    if ($scope.backupstrategy.backuptype == 0) {

        $scope.backupstrategy.backuptype = $scope.backupTypes[0];
    } else {

        $scope.backupstrategy.backuptype = $scope.backupTypes[1];
    }

    $scope.schedules = [
        {name: "每小时", value: 0},
        {name: "每天", value: 1},
        {name: "每周", value: 2},
        {name: "每月", value: 3}
    ];

    $scope.days = [
        {name: 1, value: 1}, {name: 2, value: 2}, {name: 3, value: 3}, {name: 4, value: 4}, {name: 5, value: 5},
        {name: 6, value: 6}, {name: 7, value: 7}, {name: 8, value: 8}, {name: 9, value: 9}, {name: 10, value: 10},
        {name: 11, value: 11}, {name: 12, value: 12}, {name: 13, value: 13}, {name: 14, value: 14}, {name: 15, value: 15},
        {name: 16, value: 16}, {name: 17, value: 17}, {name: 18, value: 18}, {name: 19, value: 19}, {name: 20, value: 20},
        {name: 21, value: 21}, {name: 22, value: 22}, {name: 23, value: 23}, {name: 24, value: 24}, {name: 25, value: 25},
        {name: 26, value: 26}, {name: 27, value: 27}, {name: 28, value: 28}, {name: 29, value: 29}, {name: 30, value: 30},
        {name: 31, value: 31}
    ];

    $scope.weeks = [
        {name: "星期一", value: 0},
        {name: "星期二", value: 1},
        {name: "星期三", value: 2},
        {name: "星期四", value: 3},
        {name: "星期五", value: 4},
        {name: "星期六", value: 5},
        {name: "星期天", value: 6}
    ];

    if ($scope.backupstrategy.id) {

        $scope.title = "配置策略";

        if ($scope.backupstrategy.remain != 0) {
            $scope.backupstrategy.remaindays = $scope.backupstrategy.remain;
            $scope.backupstrategy.remain = 1;
        }

        $scope.backupstrategy.backupfrequency = $scope.schedules[$scope.backupstrategy.backupfrequency];

        if ($scope.backupstrategy.weekday) {

            for (var i = 0; i < $scope.weeks.length; i++) {

                if ($scope.backupstrategy.weekday == $scope.weeks[i].name)
                    $scope.backupstrategy.week = $scope.weeks[i];
            }
        }

        if ($scope.backupstrategy.monthday) {

            $scope.backupstrategy.day = $scope.days[$scope.backupstrategy.monthday - 1];
        }

        if($scope.backupstrategy.locationtype == 0) {
            $scope.location_local();
        } else if ($scope.backupstrategy.locationtype == 1) {
            $scope.location_storage();
        } else if ($scope.backupstrategy.locationtype == 3) {
            $scope.location_remote();
        }
    } else {

        $scope.title = "新建策略";
        $scope.backupstrategy.locationtype = 0;
        $scope.location_local();

        $scope.backupstrategy.backupfrequency = $scope.schedules[0];
    }
    $scope.schedulechange();

}


/********************* Backup Strategy End  *********************/

/********************** System Guide start **********************/
function GuideDialogCtrl($scope, dialog, Util,DataCenter,$q,Cluster,$location) {
    $scope.close = function (result) {
        dialog.close(result);
    }

//    DataCenter.hosts({id:1,scope:'all'},function(data){
//       $scope.hosts = angular.element.grep(data.data,function(item){
//            return item.status == 1; //未激活
//       });
//    });

    var DATACENTER = 1,CLUSTER = 2,HOST = 3,STORAGE = 4,NETWORK = 5;
    $scope.current_step = DATACENTER;
    $scope.min_step = DATACENTER;
    var change_style = function () {
        for (var i = 0; i < NETWORK; i++) {
            var j = i + 1;
            if (j < $scope.current_step) {
                $scope['step0' + j + '_style'] = "btn-success";
            } else if (j > $scope.current_step) {
                $scope['step0' + j + '_style'] = "";
            } else {
                $scope['step0' + j + '_style'] = "btn-info";
            }
        }
    }


    $scope.$watch("current_step", function (newvalue) {
        change_style()
        $scope.error = null;
    });

    $scope.jump = function (n) {
        if(n >= $scope.min_step){
        $scope.current_step = n;
        }
    }

    $scope.prev_step = function () {
        if($scope.current_step > $scope.min_step){
            $scope.current_step -= 1;
        }
    };

    //下一步按钮状态切换
    $scope.check_inputs = function(){
        if($scope.current_step == DATACENTER){
            return !$scope.datacenter_name;
        }
        if($scope.current_step == CLUSTER){
            return !$scope.cluster_name;
        }

    }

    //完成按钮
    $scope.backtoindex = function(){
         $scope.loading = true;
            DataCenter.create({name: $scope.datacenter_name}, function (data) {
                console.log(data);
                Cluster.create({name: $scope.cluster_name, description: $scope.cluster_desc,
                        cpufamily: $scope.cluster_cpu, datacenter: data.id},
                    function (data) {
//                        $scope.current_step += 1;
                        $scope.loading = false;
//                        $scope.min_step = HOST; //数据中心和集群创建成功后不允许返回前面步骤修改
                        dialog.close();
                        window.location.href = "http://"+window.location.host;  //这里不能使用$location，$location只会刷新ng-view部分，树结构不会刷新
                    },function(e){
                        $scope.loading = false;
                        $scope.error = "集群创建失败，请重试";
                        console.log(e);
                    });
            }, function (e) {
                $scope.loading = false;
                $scope.error = "数据中心创建失败，请重试";
                console.log(e);
            });

    }
    $scope.next_step = function () {
        //集群步骤下一步
        $scope.current_step += 1;

    };

//    $scope.do_upsert = function () {
//        if ($scope.vm) {
//            new VM($scope.vm)[$scope.action](function (data) {
//                if (data.success) {
//                    if ($scope.action == "$save") {
//                        Util.update_list(dialog.context_scope.vms, $scope.vm);
//                    }
////                    Util.update_activities(data);
////                    dialog.close("Save Successful!");
//                }
//            });
//        }
//        dialog.close();
//    }
//
//    $scope.add_storage = function () {
//        $scope.selected_storage = null;
//        Util.dialog("/static/partials/storages/_storage_dialog.html", 'StorageConfigDialogCtrl', $scope, {dialogClass: 'modal mini'});
//    }
//
//    $scope.add_network = function () {
//        $scope.selected_rule = null;
//        Util.dialog("/static/partials/networks/_network_dialog.html", "NetworkConfigDialogCtrl", $scope);
//    }
}




/*********************** System Guide end ***********************/


/********************** Bookmark start **********************/
function ShortcutDialogCtrl($scope, $rootScope, Shortcut, Util, dialog) {

    $scope.do_upsert = function () {

        Shortcut.save({name: $scope.name, description: $scope.description, url: dialog.context_scope.shortcut.url},
            success = function (data) {

                dialog.close();
            },
            error = function (msg) {

                dialog.close();
                Util.alert("添加书签失败！");
            });
    };

    $scope.close = function (result) {
        dialog.close(result)
    };
};
/********************** Bookmark end ***********************/

/********** platform dialog controller start ***************/
function PlatformDialogCtrl($scope,Util,dialog, Platform){
    $scope.hardwareid = dialog.context_scope.hardwareid;
    $scope.licenseinfo = dialog.context_scope.licenseinfo;

    $scope.update = function(){
        Platform.update_license({"licenseinfo":$scope.licenseinfo},function(data){
            if(data.status==200){
                Util.alert("更新成功")
                dialog.close()
                dialog.context_scope.available = data.available
                dialog.context_scope.total = data.total
                dialog.context_scope.validity = data.validity
            }else{
                Util.alert(data.msg)
                dialog.close()
            }
        });
    }

    $scope.close = function (result) {
        dialog.close(result)
    };
}
/********** platform dialog controller end ***************/


function SnapshotDialogCtrl($scope,dialog,VM,Util,$pollingPool){
    $scope.close = function (result) {
        dialog.close(result)
    };

    $scope.save_snapshot = function(){
        VM.snapshot({id:dialog.context_scope.selected_vm.id,name:$scope.name,desc:$scope.desc},function(data){
            dialog.close();
            //快照入口是快照列表页面
            if(dialog.context_scope.from_list){
                $pollingPool.add_activity_callback(data.activity,function(){
                    dialog.context_scope.snapshots.push(data);
                })
            }
            console.log(data);
        })
    }
}

function SnapshotRestoreDialogCtrl($scope,dialog,VM){
    $scope.close = function (result) {
        dialog.close(result)
    };

    $scope.select = function(){
        $scope.snap = this.snapshot;
    }

    VM.snapshot_list({id:dialog.context_scope.selected_vm.id,scope:'all'},function(data){
        $scope.snapshots = data.data;
    })

    $scope.restore_snapshot = function(){
        VM.snapshot_restore({id:dialog.context_scope.selected_vm.id,snap_id:$scope.snap.id},function(data){
            dialog.close();
            console.log(data);
        })
    }

}


function attach_disk_ctrl($scope,Cluster,dialog,$pollingPool,Util,$routeParams,VM){
   $scope.page_size = 5;
   $scope.close = function(){
       dialog.close();
   }
    $scope.disk = dialog.context_scope.selected_disk;
    $scope.select = function(){
        $scope.selected_vm = this.vm;
    }

    $scope.service = function (start, limit) {
        Cluster.vms({id: $routeParams.id,current_page: start, page_size: limit},function(data){
            $scope.vms = data.data;
            $scope.total_page = data.total_page;
            $scope.total_count = data.total_count;
        })
    };

    Util.paginate($scope, 'vms');


    $scope.attach_disk = function(){
        VM.attach_disk({id:$scope.selected_vm.id,disk:$scope.disk.id},function(data){
            $pollingPool.add_activity_callback(data.activity,function(){
                dialog.context_scope.selected_disk.instance = data.instance;
            })
            dialog.close();
        })
    }
}


function VMCloneDialogCtrl($scope,VM,dialog,Cluster,$pollingPool,ztree,$filter){
    $scope.title = "克隆虚拟机";
    $scope.close = function(){
        dialog.close();
    }

    $scope.vm = dialog.context_scope.selected_vm;
    $scope.newvm = {name:$scope.vm.name+'_clone'};

    $scope.newvm.storage = {};//disk.name+disk.id : storage
    $scope.newvm.network = {};//iface.name+iface.id : network
    $scope.newvm.samecdrom = true;

    Cluster.networks({id:$scope.vm.host.cluster.id,scope:'all'},function(data){
        $scope.networks = data.data;
        //disk.network不能对应查询出来的networks，所以我们匹配一下
        angular.forEach($scope.networks,function(s){
            angular.forEach($scope.vm.interface_set,function(iface){
                if (iface.enable){
                    if(iface.network.id == s.id){
                        $scope.newvm.network[iface.name+iface.id] = s;
                    }
                }
            })
        })
    })

    Cluster.storages({id:$scope.vm.host.cluster.id,scope:'all'},function(data){
        $scope.storages = $.grep(data.data,function(item){
            return item.type != 'iso' && item.protocol != 'local' && item.protocol != 'iscsi';
        })
        //disk.storage不能对应查询出来的storages，所以我们匹配一下
        angular.forEach($scope.storages,function(s){
            angular.forEach($scope.vm.vdisk_set,function(disk){
                if (disk.device_type!='cdrom'){
                    if(disk.storage.id == s.id){
                        $scope.newvm.storage[disk.name+disk.id] = s;
                    }
                }
            })
        })

    })

    Cluster.hosts({id:$scope.vm.host.cluster.id,scope:'all'},function(data){
        $scope.hosts = data.data;
        angular.forEach($scope.hosts,function(item){
            if(item.id == $scope.vm.host.id){
                $scope.newvm.host = item;
            }
        })
    })

    $scope.do_clone = function(){
        dialog.close()
        VM.clone({id:$scope.vm.id,newvm:$scope.newvm},function(data){
            $pollingPool.add_activity_callback(data.activity,function(){
                   dialog.context_scope.vms.push(data);
                   ztree.addvm({
                       id: data.id,
                       name: data.name,
                       url: "#/vm/" + data.id,
                       icon:"/static/images/vmstatus/"+$filter('lowercase')($scope.newvm.status)+".png"
                   }, data.host.id);
               })
        })
    }


}
function showImageCtrl($scope,dialog){
    $scope.close = function(){
        dialog.close();
    }
    $scope.image_url = dialog.context_scope.image_url;
}

function userDialogCtrl($scope,dialog,User){
    $scope.close = function(){
        dialog.close();
    }

    $scope.title = dialog.context_scope.title;
    $scope.method = dialog.context_scope.method;

    if($scope.method=='update'){
        $scope.user = angular.copy(dialog.context_scope.selected_user);
    }

    $scope.upset = function(){
        dialog.close();
        if($scope.method=='create'){
            User.create({user:$scope.user},function(data){
                dialog.context_scope.users.push(data);
            })
        }else if($scope.method=='update'){
            User.update({id:$scope.user.id,user:$scope.user},function(data){
                dialog.context_scope.selected_user.password = $scope.user.password;
                dialog.context_scope.selected_user.organize = $scope.user.organize;
                dialog.context_scope.selected_user.phone = $scope.user.phone;
            })
        }

    }


}


function attach_vm_ctrl($scope,VM,dialog,Util,User){
   $scope.page_size = 5;
   $scope.close = function(){
       dialog.close();
   }
    $scope.selected = {};

    angular.forEach(dialog.context_scope.selected_user.instance_set,function(vm){
        $scope.selected[vm.id] = true;
    })

    $scope.service = function (start, limit) {
        VM.list({current_page: start, page_size: limit,nouser:true},function(data){
            $scope.vms = data.data;
            $scope.total_page = data.total_page;
            $scope.total_count = data.total_count;
        })
    };

    Util.paginate($scope, 'vms');


    $scope.do_attach = function(){

        var ids = [];
        var vm_set = [];
        for (k in $scope.selected){
            if($scope.selected[k]){
                ids.push(k);
                vm_set.push({id:k})
            }
        }

        User.attach({ids:ids,id:dialog.context_scope.selected_user.id},function(data){
            dialog.context_scope.selected_user.instance_set = vm_set;

            dialog.close();
        })
    }
}